#/bin/bash
CG_ROOT_DIR="/cgroup/"
CG_CPUSET_DIR="$CG_ROOT_DIR/cpuset"
CG_CPU_DIR="$CG_ROOT_DIR/cpu"
CG_MEM_DIR="$CG_ROOT_DIR/memory"
CONF="/usr/local/cgroup/cgconfig"

if [ $# -lt 1 ];then

	     /bin/echo "useage:  cglichctrl.sh  create  configname"
	     /bin/echo "         cglichctrl.sh  delete  kvmname" 
	     exit 
fi

#if [ ! -f "$CONF" ];then
#        /bin/echo not found config file $CONF,exit..
#        exit 3
#fi
#check cgroup status
if ! service cgconfig status |grep -i running > /dev/null;then
        /bin/echo "cgconfig service not start"
        exit 1;
fi

if [ "$1" == "delete" ];then
	for set in cpuset cpu memory
	do
		cgdelete -r $set:/lich

	done

	exit;
fi

pid=$(ps aux |grep lichd |grep -v grep |grep  -v $0|awk '{print $2}')

if [ -z "$pid" ];then
	/bin/echo "lichd not start\n"
	exit 1
fi	

config=$2;

if [ -z "$config" ];then
	/bin/echo please set config
	exit 2
fi

if [ ! -f "$config" ];then
	/bin/echo not found $config
	exit 2
fi

. $config

if [ $? != 0 ];then
	/bin/echo load config $config failed 
	exit 2
fi

MEM_NODE=`cat /proc/zoneinfo  |grep Node |awk  -F ",| " 'BEGIN{ORS=","}{a[$2]++}END{for(i in a){print i}}'|sed 's/,$//'`
for dir in cpu memory cpuset
do

	if [ "$dir" == "cpu" ];then
		mkdir -p $CG_ROOT_DIR/cpu/lich
#		/bin/echo period $PERIOD_US
		/bin/echo $PERIOD_US > $CG_ROOT_DIR/cpu/lich/cpu.rt_period_us
#		/bin/echo runtime $RUNTIME_US
		/bin/echo $RUNTIME_US > $CG_ROOT_DIR/cpu/lich/cpu.rt_runtime_us
	elif [ "$dir" == "cpuset" ];then
		mkdir -p  $CG_ROOT_DIR/cpuset/lich
		echo memnode $MEM_NODE
#		echo $CG_ROOT_DIR/cpuset/qemu/$qemu_dir/cpuset.mems
		/bin/echo $MEM_NODE > $CG_ROOT_DIR/cpuset/lich/cpuset.mems
		/bin/echo cpuset $CPUSET
		/bin/echo $CPUSET   > $CG_ROOT_DIR/cpuset/lich/cpuset.cpus
		
	elif [ "$dir" == "memory" ];then
		mkdir -p $CG_ROOT_DIR/memory/lich

		if test -f  $CG_ROOT_DIR/memory/lich/memory.oom_control ;then
			/bin/echo 1 >  $CG_ROOT_DIR/memory/lich/memory.oom_control
		fi
		/bin/echo swap $SWAP
		/bin/echo $SWAP > $CG_ROOT_DIR/memory/lich/memory.swappiness
		/bin/echo MEMLIMIT $MEMLIMIT
		/bin/echo $MEMLIMIT > $CG_ROOT_DIR/memory/lich/memory.limit_in_bytes
	fi

	for p in $pid
	do
		for tid in $(ls /proc/$p/task)
        	do
	#	echo tid $tid
                	/bin/echo  $tid >  $CG_ROOT_DIR/$dir/lich/tasks
        	done
	done

done

